#_*_ encoding:utf-8 _*_
from django.http import HttpResponseRedirect,HttpResponse,JsonResponse
from django.contrib.contenttypes.models import ContentType
from django.views.generic import View,TemplateView
from django.shortcuts import render
from common.viewbase import LoginRequiredBaseView,CreateBaseView,DeleteBaseView
from .forms import *
from .models import *
import json

# 查询表的工作流
def find_workflow(app,model):
    content_type = ContentType.objects.get(app_label=app,model=model)
    workflows = WorkFlow.objects.filter(content_type=content_type,is_open=True).order_by('-id')
    if workflows.count() > 0:
        workflow = workflows[0]
    else:
        workflow = ''
    return workflow

def get_image(node,color='blue'):
    max_step = Node.objects.filter(workflow_id=node.workflow_id).order_by('-step')[0].step
    if node.step == 1:
        url = '/static/images/submit_%s.svg' % color
    elif node.step == max_step:
        url = '/static/images/finish_%s.svg' % color
    elif NodeProcess.objects.filter(nextnode=node,kind=2).count():
        url = '/static/images/edit_%s.svg' % color
    else:
        url = '/static/images/shenhe_%s.svg' % color
    return url

class WorkFlowOverView(TemplateView,LoginRequiredBaseView):
    template_name = 'workflow_overview.html'

    def post(self,request):
        flowid = request.POST.get('id','')
        data = {'nodes':[],'edges':[],'is_open':''}
        if flowid:
            workflow = WorkFlow.objects.get(id=flowid)
            nodes = Node.objects.filter(workflow=workflow)
            if workflow.is_open:
                data['is_open'] = u'已启用'
            else:
                data['is_open'] = u'已关闭'
            for node in nodes:
                data['nodes'].append({'id': node.id, 'label':node.name,'level':node.step,'font':{'color':'#fff','size':14,'strokeWidth':3,'strokeColor':'#3B99FC'},'image': get_image(node), 'shape': 'image'})
                for n in node.process.all():
                    data['edges'].append({'id':n.id,'from':node.id,'to':n.nextnode.id,'label':n.get_kind_display(),'font':{'color':'#000','size':10,'align': 'middle'}})
        return JsonResponse(data)

    def get_context_data(self, **kwargs):
        context = super(WorkFlowOverView, self).get_context_data()
        workflow = WorkFlow.objects.all()
        context.update({
            'workflow':workflow,
            'WorkFlowForm':WorkFlowForm().as_ul(),
            'NodeForm':NodeForm().as_ul(),
        })
        return context

class GetNodeProcessForm(View):
    name = '获取工作流节点表单'

    def post(self,request):
        workflow_id = self.request.POST.get('id','')
        form = PartNodeProcessForm(workflow_id).as_ul()
        return HttpResponse(form)

class AddWorkFlowView(CreateBaseView):
    name = '新增工作流'
    form = WorkFlowForm
    model = WorkFlow

    def before_save(self):
        name = self.request.POST.get('name','')
        if name:
            if WorkFlow.objects.filter(name=name).count():
                return JsonResponse({'status':False,'msg':'该工作流已存在'})
        else:
            return JsonResponse({'status':False,'msg':'请输入工作流名称'})

    def success_fuc(self,obj):
        return JsonResponse({'status':True,'refresh':True})

class AddNodeView(CreateBaseView):
    name = '新增节点'
    form = NodeForm
    model = Node

    def before_save(self):
        name = self.request.POST.get('name','')
        workflow_id = self.request.POST.get('workflow_id','')
        if name:
            if Node.objects.filter(name=name,workflow_id=workflow_id).count():
                return JsonResponse({'status':False,'msg':'该节点名已存在'})
        else:
            return JsonResponse({'status':False,'msg':'请输入节点名'})

    def other_dict(self):
        workflow_id = self.request.POST.get('workflow_id','')
        return {'workflow_id':workflow_id}

    def success_fuc(self,obj):
        return JsonResponse({'status':True,'refresh':False,'id':obj.workflow_id})

class AddNodeProcessView(CreateBaseView):
    name = '新增节点流程'
    form = NodeProcessForm
    model = NodeProcess

    def other_dict(self):
        nextnode = self.request.POST.get('nextnode','')
        return {'nextnode_id':nextnode}

    def after_save(self,obj):
        node_id = self.request.POST.get('node_id','')
        node = Node.objects.get(id=node_id)
        node.process.add(obj)

    def success_fuc(self,obj):
        return JsonResponse({'status':True,'refresh':False,'id':obj.nextnode.workflow_id})

class DeleteNodeViews(DeleteBaseView):
    name = '删除节点'
    model = Node

    def before_delete(self):
        node_id = self.request.POST.get('id','')
        node = Node.objects.get(id=node_id)
        # 删除下级多对多
        for n in node.process.all():
            node.process.remove(n)
            n.delete()
        # 删除上级多对多
        other_nodes = NodeProcess.objects.filter(nextnode_id=node_id)
        for o in other_nodes:
            for x in o.node_process.all():
                x.process.remove(o)

    def success_fuc(self,obj):
        return JsonResponse({'status':True,'redraw':True,'id':obj['workflow_id']})

class DeleteNodeProcessViews(DeleteBaseView):
    name = '删除节点流程'
    model = NodeProcess

    def before_delete(self):
        nodeprocess_id = self.request.POST.get('id','')
        p = NodeProcess.objects.get(id=nodeprocess_id)
        for n in p.node_process.all():
            n.process.remove(p)

    def success_fuc(self,obj):
        node = Node.objects.get(id=obj['nextnode_id'])
        return JsonResponse({'status':True,'redraw':True,'id':node.workflow_id})

class WorkFlowApprovalView(TemplateView,LoginRequiredBaseView):
    template_name = 'workflow_approval.html'

    def get_context_data(self, **kwargs):
        context = super(WorkFlowApprovalView, self).get_context_data()
        workflow_id = self.request.GET.get('workflow_id','')
        detail_id = self.request.GET.get('detail_id','')
        user = self.request.user
        history = History.objects.get(workflow_id=workflow_id,detail_id=detail_id)
        details = HistoryDetail.objects.filter(history=history)
        details_nodes = [i.node.id for i in details]

        workflow = WorkFlow.objects.get(id=workflow_id)
        data = {'nodes':[],'edges':[]}
        nodes = Node.objects.filter(workflow=workflow)
        for node in nodes:
            if history.node.id == node.id:
                color = 'red'
                strokeColor = '#E74C3C'
            elif node.id in details_nodes:
                color = 'green'
                strokeColor = '#00B131'
            else:
                color = 'gray'
                strokeColor = '#ccc'
            data['nodes'].append({'id': node.id, 'label':node.name,'level':node.step,'font':{'color':'#fff','size':14,'strokeWidth':3,'strokeColor':strokeColor},'image': get_image(node,color), 'shape': 'image'})
            for n in node.process.all():
                if details.filter(node=node,status=n.kind+1).count() > 0:
                    edge_color = '#00B131'
                else:
                    edge_color = '#ccc'
                data['edges'].append({'id':n.id,'from':node.id,'to':n.nextnode.id,'label':n.get_kind_display(),'color':edge_color,'font':{'color':edge_color,'size':10,'align': 'middle'}})
        for d in details:
            d.image = get_image(d.node)
        context.update({
            'data':json.dumps(data),
            'details':details
        })
        return context

def create_history(workflow_id,detail_id,user):
    status = False
    history = History.objects.filter(workflow_id=workflow_id,detail_id=detail_id).exclude(status=4)
    if history.count() > 0:
        msg = u'请勿重复提交申请'
    else:
        node = Node.objects.filter(workflow_id=workflow_id,step=1)[0]
        obj = History.objects.create(workflow_id=workflow_id,detail_id=detail_id,user=user,node=node,status=1)
        HistoryDetail.objects.create(history=obj,node=node,status=1)
        status = True
        msg = u'申请已提交'
    data = {'status':status,'msg':msg}
    return data

class CreateHistory(View):
    name = '提交工作流申请'

    def post(self,request):
        workflow_id = request.POST.get('workflow_id','')
        detail_id = request.POST.get('detail_id','')
        data = create_history(workflow_id,detail_id,request.user)
        return JsonResponse(data)

def update_history(workflow_id,detail_id,kind,content,user):
    status = False
    if kind:
        history = History.objects.filter(workflow_id=workflow_id,detail_id=detail_id).exclude(status=4)
        if history.count() > 0:
            history = history[0]
            kind = int(kind)
            nextnode = history.node.process.filter(kind=kind)[0].nextnode
            node = history.node
            history.node = nextnode
            max_step = Node.objects.filter(workflow_id=workflow_id).order_by('-step')[0].step
            if nextnode.step == max_step:               # 最后一步就是完成
                history.status = 2
            if kind == 2:
                history.status = 3
            if kind == 1 and history.status == 3:
                history.status = 1
            history.save()
            HistoryDetail.objects.create(history=history,node=node,status=(kind+1),approve_person=user,content=content)
            status = True
    return status

class UpdateHistory(View):
    name = '更新工作流进度'

    def post(self,request):
        workflow_id = request.POST.get('workflow_id','')
        detail_id = request.POST.get('detail_id','')
        kind = request.POST.get('kind','')              # 1:审批通过, 2:审批不通过
        content = request.POST.get('content','')
        status = update_history(workflow_id,detail_id,kind,content,request.user)
        return JsonResponse({'status':status})

class OpenOrClose(View):
    name = '切换工作流状态'

    def post(self,request):
        workflow_id = request.POST.get('workflow_id','')
        workflow = WorkFlow.objects.get(id=workflow_id)
        if workflow.is_open:
            workflow.is_open = False
            workflow.save()
        else:
            workflow.is_open = True
            workflow.save()
        return JsonResponse({'status':True,'msg':u'状态切换成功'})